package com.jackrain.nea.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jackrain.nea.config.PropertiesConf;
import com.jackrain.nea.core.schema.*;
import com.jackrain.nea.core.webaction.WebAction;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.LimitQueue;
import com.jackrain.nea.util.RedisOpsUtil;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.face.User;
import com.jackrain.nea.web.face.impl.UserImpl;
import com.jackrain.nea.web.model.MenuObject;
import com.jackrain.nea.web.model.UserConfig;
import com.jackrain.nea.web.query.QueryEngine;
import com.jackrain.nea.web.query.QuerySessionImpl;
import com.jackrain.nea.web.query.SubSystemView;
import com.jackrain.nea.web.security.SecurityWebUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * Created by Lucky dog on 2017/7/27.
 */
@Slf4j
@RestController
@Api(value = "MenuController", description = "顶部和侧边栏菜单接口")
public class MenuController {

    private SubSystemView subSystemView = new SubSystemView();;

    @ApiOperation(value = "获取切换菜单")
    @RequestMapping(path = "/p/cs/getSubSystems",method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject getSubSystems(HttpServletRequest request){
        ValueHolder vh = new ValueHolder();
        User user = (UserImpl)request.getSession().getAttribute("user");
        try {
            List<ArrayList> list = this.subSystemView.getModels(request,0);
            JSONArray models = new JSONArray();
            for(ArrayList model : list){
                JSONObject modelJO = new JSONObject();
                modelJO.put("id",((SysModel)model.get(0)).getId());
                modelJO.put("value",((SysModel)model.get(0)).getId());
                modelJO.put("label",((SysModel)model.get(0)).getName());
                modelJO.put("level","SysModel");
                JSONArray subs = new JSONArray();
                for(ArrayList sub : (List<ArrayList>)model.get(1)){
                    JSONObject subJO = new JSONObject();
                    subJO.put("id",((SubSystem)sub.get(0)).getId());
                    subJO.put("value",((SubSystem)sub.get(0)).getId());
                    subJO.put("label",((SubSystem)sub.get(0)).getName());
                    subJO.put("level","SubSystem");
                    JSONArray categorys = new JSONArray();
                    for(ArrayList category : (List<ArrayList>)sub.get(1)){
                        JSONObject categoryJO = new JSONObject();
                        categoryJO.put("id",((TableCategory)category.get(0)).getId());
                        categoryJO.put("value",((TableCategory)category.get(0)).getId());
                        categoryJO.put("label",((TableCategory)category.get(0)).getDescription(user.getLocale()));
                        categoryJO.put("level","TableCategory");
                        List lists = (ArrayList)category.get(1);
                        JSONArray children = new JSONArray();
                        for(Object o : lists){
                            JSONObject jo = new JSONObject();
                            if(o instanceof Table){
                                jo.put("id",((Table) o).getId());
                                jo.put("value",((Table) o).getName());
                                jo.put("label",((Table) o).getDescription(user.getLocale()));
                                jo.put("type","table");
                            }else if(o instanceof WebAction){
                                if(((WebAction) o).getDisplayType().equals(WebAction.DisplayTypeEnum.Accord)){
                                    jo.put("id",((WebAction) o).getId());
                                    jo.put("value",((WebAction) o).getName());
                                    jo.put("label",((WebAction) o).getDescription(user.getLocale()));
                                    jo.put("webaction", JSON.parseObject(((WebAction) o).getScript()));
                                    jo.put("type","action");
                                }
                            }
                            children.add(jo);
                        }
                        categoryJO.put("children",children);
                        categorys.add(categoryJO);
                    }
                    subJO.put("children",categorys);
                    subs.add(subJO);
                }
                modelJO.put("children",subs);
                models.add(modelJO);
            }

            vh.put("code",0);
            vh.put("data", models);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            vh.put("code",-1);
            vh.put("message",e.getMessage());
        }finally {
            return vh.toJSONObject();
        }
    }

    @ApiOperation(value = "获取表类别下Children")
    @RequestMapping(path = "/p/cs/getTableCategoryChildren",method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject getTableCategoryChildren(HttpServletRequest request,
                                               @RequestParam(value="tableCategory", required=true)int tableCategoryId){
        QuerySessionImpl querySession = new QuerySessionImpl(request);
        ValueHolder vh = new ValueHolder();
        try {
            List lists = this.subSystemView.getChildrenOfTableCategory(request,tableCategoryId,true);
            JSONArray children = new JSONArray();
            for(Object o : lists){
                JSONObject jo = new JSONObject();
                if(o instanceof Table){
                    jo.put("id",((Table) o).getId());
                    jo.put("value",((Table) o).getName());
                    jo.put("label",((Table) o).getDescription(querySession.getLocale()));
                    jo.put("type","table");
                }else if(o instanceof WebAction){
                    if(((WebAction) o).getDisplayType().equals(WebAction.DisplayTypeEnum.Accord)){
                        jo.put("id",((WebAction) o).getId());
                        jo.put("value",((WebAction) o).getName());
                        jo.put("label",((WebAction) o).getDescription(querySession.getLocale()));
                        jo.put("webaction", JSON.parseObject(((WebAction) o).getScript()));
                        jo.put("type","action");
                    }
                }
                children.add(jo);
            }
            vh.put("code",0);
            vh.put("data", children);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            vh.put("code",-1);
            vh.put("message",e.getMessage());
        }finally {
            return vh.toJSONObject();
        }
    }

    @ApiOperation(value = "获取店铺")
    @RequestMapping(path = "/p/cs/getStore",method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject getStore(HttpServletRequest request){
        ValueHolder vh = new ValueHolder();
        UserImpl userWeb= (UserImpl)request.getSession().getAttribute("user");
        int storeId = userWeb.getStoreId();
        JSONObject o = QueryEngine.getInstance().doQueryObject("select ID AS STOREID,STORENAME,IMAGE AS STOREIMAGE from C_STORE WHERE ID=?",new Object[]{storeId});
        vh.put("code",0);
        vh.put("data",o);
        return vh.toJSONObject();
    }

    @ApiOperation(value = "获取历史浏览和收藏夹")
    @RequestMapping(path = "/p/cs/getHistoryAndFavorite",method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject getHistoryAndFavorite(HttpServletRequest request){
        ValueHolder vh = new ValueHolder();
        UserImpl userWeb= (UserImpl)request.getSession().getAttribute("user");

        RedisOpsUtil<String,LimitQueue<MenuObject>> redisOpsUtil = ApplicationContextHandle.getBean(RedisOpsUtil.class);
        LimitQueue<MenuObject> queue = (LimitQueue<MenuObject>) redisOpsUtil.objRedisTemplate.opsForHash().get("History",userWeb.getId().toString());
        ArrayList<MenuObject> list = (ArrayList<MenuObject>) redisOpsUtil.objRedisTemplate.opsForHash().get("Favorite",userWeb.getId().toString());
        JSONObject jo = new JSONObject();
        jo.put("history",queue);
        jo.put("favorite",list);
        vh.put("code",0);
        vh.put("data",jo);

        return vh.toJSONObject();
    }

    @ApiOperation(value = "记住历史浏览")
    @RequestMapping(path = "/p/cs/recHistory",method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject recHistory(HttpServletRequest request,
                                 @RequestParam(value="url", required=true)String url,
                                 @RequestParam(value="type", required=true)String type,
                                 @RequestParam(value="id", required=true)int id){
        ValueHolder vh = new ValueHolder();
        UserImpl userWeb= (UserImpl)request.getSession().getAttribute("user");
        QuerySessionImpl querySession = new QuerySessionImpl(request);
        TableManager tm = querySession.getTableManager();

        MenuObject menuObject = null;
        if(type.equals("table")){
            Object o = tm.getTable(id);
            menuObject = new MenuObject();
            menuObject.setId(((Table) o).getId());
            menuObject.setType("table");
            menuObject.setValue(((Table) o).getName());
            menuObject.setLabel(((Table) o).getDescription(querySession.getLocale()));
            menuObject.setUrl(url);
        }else  if(type.equals("action")){
            Object o = tm.getWebAction(id);
            menuObject = new MenuObject();
            menuObject.setId(((WebAction) o).getId());
            menuObject.setType("action");
            menuObject.setValue(((WebAction) o).getName());
            menuObject.setLabel(((WebAction) o).getDescription(querySession.getLocale()));
            menuObject.setWebaction(JSON.parseObject(((WebAction) o).getScript()));
            menuObject.setUrl(url);
        }
        if(menuObject == null){
            vh.put("code",-1);
            vh.put("message","Object cannot be found in schema");
            return vh.toJSONObject();
        }
        RedisOpsUtil<String,LimitQueue<MenuObject>> redisOpsUtil = ApplicationContextHandle.getBean(RedisOpsUtil.class);
        LimitQueue<MenuObject> queue = (LimitQueue<MenuObject>) redisOpsUtil.objRedisTemplate.opsForHash().get("History",userWeb.getId().toString());
        if(queue == null){
            queue = new LimitQueue<MenuObject>(10);
            queue.offer(menuObject);
        }else{
            queue.remove(menuObject);
            queue.offer(menuObject);
        }
        redisOpsUtil.objRedisTemplate.opsForHash().put("History",userWeb.getId().toString(),queue);

        vh.put("code",0);
        vh.put("data",queue);

        return vh.toJSONObject();
    }

    @ApiOperation(value = "添加收藏")
    @RequestMapping(path = "/p/cs/addToFavorite",method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject addToFavorite(HttpServletRequest request,
                                    @RequestParam(value="url", required=true)String url,
                                 @RequestParam(value="type", required=true)String type,
                                 @RequestParam(value="id", required=true)int id){
        ValueHolder vh = new ValueHolder();
        UserImpl userWeb= (UserImpl)request.getSession().getAttribute("user");
        QuerySessionImpl querySession = new QuerySessionImpl(request);
        TableManager tm = querySession.getTableManager();

        MenuObject menuObject = null;
        if(type.equals("table")){
            Object o = tm.getTable(id);
            menuObject = new MenuObject();
            menuObject.setId(((Table) o).getId());
            menuObject.setType("table");
            menuObject.setValue(((Table) o).getName());
            menuObject.setLabel(((Table) o).getDescription(querySession.getLocale()));
            menuObject.setUrl(url);
        }else  if(type.equals("action")){
            Object o = tm.getWebAction(id);
            menuObject = new MenuObject();
            menuObject.setId(((WebAction) o).getId());
            menuObject.setType("action");
            menuObject.setValue(((WebAction) o).getName());
            menuObject.setLabel(((WebAction) o).getDescription(querySession.getLocale()));
            menuObject.setWebaction(JSON.parseObject(((WebAction) o).getScript()));
            menuObject.setUrl(url);
        }

        if(menuObject == null){
            vh.put("code",-1);
            vh.put("message","Object cannot be found in schema");
            return vh.toJSONObject();
        }

        RedisOpsUtil<String,ArrayList<MenuObject>> redisOpsUtil = ApplicationContextHandle.getBean(RedisOpsUtil.class);
        ArrayList<MenuObject> list = (ArrayList<MenuObject>) redisOpsUtil.objRedisTemplate.opsForHash().get("Favorite",userWeb.getId().toString());
        if(list == null){
            list = new ArrayList<MenuObject>();
        }
        if(!list.contains(menuObject)){
            list.add(menuObject);
            redisOpsUtil.objRedisTemplate.opsForHash().put("Favorite",userWeb.getId().toString(),list);
        }
        vh.put("code",0);
        vh.put("data",list);

        return vh.toJSONObject();
    }

    @ApiOperation(value = "取消收藏")
    @RequestMapping(path = "/p/cs/removeFromFavorite",method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject removeFromFavorite(HttpServletRequest request,
                                    @RequestParam(value="type", required=true)String type,
                                    @RequestParam(value="id", required=true)int id){
        ValueHolder vh = new ValueHolder();
        UserImpl userWeb= (UserImpl)request.getSession().getAttribute("user");
        QuerySessionImpl querySession = new QuerySessionImpl(request);
        TableManager tm = querySession.getTableManager();

        MenuObject menuObject = null;
        if(type.equals("table")){
            Object o = tm.getTable(id);
            menuObject = new MenuObject();
            menuObject.setId(((Table) o).getId());
            menuObject.setType("table");
            menuObject.setValue(((Table) o).getName());
            menuObject.setValue(((Table) o).getDescription(querySession.getLocale()));
        }else  if(type.equals("action")){
            Object o = tm.getWebAction(id);
            menuObject = new MenuObject();
            menuObject.setId(((WebAction) o).getId());
            menuObject.setType("action");
            menuObject.setValue(((WebAction) o).getName());
            menuObject.setLabel(((WebAction) o).getDescription(querySession.getLocale()));
            menuObject.setWebaction(JSON.parseObject(((WebAction) o).getScript()));
        }

        RedisOpsUtil<String,LimitQueue<MenuObject>> redisOpsUtil = ApplicationContextHandle.getBean(RedisOpsUtil.class);
        ArrayList<MenuObject> list = (ArrayList<MenuObject>) redisOpsUtil.objRedisTemplate.opsForHash().get("Favorite",userWeb.getId().toString());

        list.remove(menuObject);
        redisOpsUtil.objRedisTemplate.opsForHash().put("Favorite",userWeb.getId().toString(),list);

        vh.put("code",0);
        vh.put("data",list);

        return vh.toJSONObject();
    }

    @ApiOperation(value = "获取消息通知")
    @RequestMapping(path = "/p/cs/getUNote",method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject getUNote(HttpServletRequest request){

        ValueHolder vh = new ValueHolder();
        UserImpl userWeb= (UserImpl)request.getSession().getAttribute("user");
        String sql = "SELECT  ID,TITLE,PRIORITYRULE,MODIFIEDDATE,DESCRIPTION FROM U_NOTE\n" +
                "WHERE DOCSTATUS='INIT' AND USER_ID=? ORDER BY MODIFIEDDATE LIMIT 0,5";

        JSONArray ja = QueryEngine.getInstance().doQueryObjectArray(sql,new Object[]{userWeb.getId()});


        vh.put("code",0);
        vh.put("data",ja);

        return vh.toJSONObject();
    }

    @ApiOperation(value = "更改消息通知")
    @RequestMapping(path = "/p/cs/markReadUNote",method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject markReadUNote(HttpServletRequest request,  @RequestParam(value="id", required=true)long id){
        ValueHolder vh = new ValueHolder();
        UserImpl userWeb= (UserImpl)request.getSession().getAttribute("user");
        String sql = "UPDATE U_NOTE SET DOCSTATUS='READ',MODIFIEDDATE=NOW(),MODIFIERID=? WHERE ID=?";
        QueryEngine.getInstance().executeUpdate(sql,new Object[]{userWeb.getId(),id});
        vh.put("code",0);
        vh.put("message","success");

        return vh.toJSONObject();
    }

    @ApiOperation(value = "设置列表隐藏字段")
    @RequestMapping(path = "/p/cs/setHideColumn",method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject setHideColumn(HttpServletRequest request,
                                   @RequestParam(value="tableid", required=true)long tableId,
                                   @RequestParam(value="hidecolumns", required=true)String hideColumn){
        ValueHolder vh = new ValueHolder();
        //UserImpl userWeb= (UserImpl)request.getSession().getAttribute("user");
        User userWeb= SecurityWebUtils.getUser(893);

        RedisOpsUtil<String,UserConfig> redisOpsUtil = ApplicationContextHandle.getBean(RedisOpsUtil.class);
        UserConfig userConfig = (UserConfig) redisOpsUtil.objRedisTemplate.opsForHash().get("UserConfig",userWeb.getId().toString());
        if(userConfig == null){
            userConfig = new UserConfig();
        }
        userConfig.addHideColumn(tableId,hideColumn);
        redisOpsUtil.objRedisTemplate.opsForHash().put("UserConfig",userWeb.getId().toString(),userConfig);

        vh.put("code",0);
        vh.put("data",hideColumn);

        return vh.toJSONObject();
    }

}
